package user

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"shejiao/base"
	"shejiao/common/model/user"
	"time"
)

var AuthService = authService{grom: base.Mysql}

type authService struct {
	grom *gorm.DB
}

// Get 获取授权信息
func (a *authService) Get(openId string) (user.UserAuth, user.UserInfo, user.UserToken) {
	var ua user.UserAuth
	var ui user.UserInfo
	var ut user.UserToken
	fmt.Println("mysql", base.Mysql)
	base.Mysql.Find(&ua, "open_id = ?", openId)

	if ua.Id != 0 {
		base.Mysql.Find(&ui, "user_id = ?", ua.Id)
		base.Mysql.Find(&ut, "user_id = ?", ua.Id)
	}

	return ua, ui, ut
}

// Get 获取授权信息
func (a *authService) GetById(userId int64) (user.UserAuth, user.UserInfo, user.UserToken) {
	var ua user.UserAuth
	var ui user.UserInfo
	var ut user.UserToken
	base.Mysql.Find(&ua, "id = ?", userId)

	if ua.Id != 0 {
		base.Mysql.Find(&ui, "user_id = ?", ua.Id)
		base.Mysql.Find(&ut, "user_id = ?", ua.Id)
	}

	return ua, ui, ut
}

// Register 用户注册
func (a *authService) Register(openId string) (user.UserAuth, user.UserInfo, user.UserToken, error) {
	now := time.Now().Unix()
	userAuth := user.UserAuth{OpenId: openId, CreateAt: now, UpdateAt: now}
	userInfo := user.UserInfo{}
	userToken := user.UserToken{}

	// 注册用户授权表
	err := base.Mysql.Create(&userAuth).Error
	if err != nil || userAuth.Id == 0 {
		return userAuth, userInfo, userToken, errors.New("注册失败")
	}

	// 注册用户信息表
	userInfo = user.UserInfo{UserId: userAuth.Id, CreateAt: userAuth.CreateAt, UpdateAt: userAuth.UpdateAt}
	err = base.Mysql.Create(&userInfo).Error
	if err != nil {
		return userAuth, userInfo, userToken, errors.New("注册用户信息失败")
	}

	// 用户钻石资源表
	userToken = user.UserToken{Type: user.UserTokenTypeDiamond, UserId: userAuth.Id, CreateAt: userAuth.CreateAt, UpdateAt: userAuth.UpdateAt}
	err = base.Mysql.Create(&userToken).Error
	if err != nil {
		return userAuth, userInfo, userToken, errors.New("注册用户信息失败")
	}

	return userAuth, userInfo, userToken, nil
}
